import axios from 'axios'
import router from './router'
import qs from 'qs'

axios.interceptors.request.use((config) => {
  if(config.method == 'post' || config.method == 'put' || config.method == 'patch') {
    config.data = config.data || {}
    let has_files = false
    for(let i in config.data) {
      if(config.data[i] instanceof File) {
        has_files = true
        break
      }
    }

    if(has_files) {
      const formdata = new FormData()
      for(let i in config.data) {
        formdata.append(i, config.data[i])
      }
      config.data = formdata
    } else {
      config.data = qs.stringify(config.data)
    }
  }
  return config
})

axios.interceptors.response.use((res) => {
  const url = res.config.url
  if(res.status == 200) {
    res = res.data
    // if(url.substr(0, 11) == '/easy_stock') {
    //   if(res.code == -1 || res.code == -2) {
    //     router.replace({name: 'Login'})
    //   }
    // }
    return res
  }
}, function(err) {
  return Promise.reject(err)
})
